package com.cjc.sport.controller;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * ========================
 * Created with intellij IDEA
 * 创建者：杜一平
 * 日期：2017/1/19（星期五）
 * 时间：08：00
 * 说明：该类为下面的控制器提供解析json工具
 * ==========================
 */

public class BaseController {
    /**
     * 定义日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(BaseController.class);

    /**
     * 解析json对象
     *
     * @param request 请求对象
     * @return JsonObject json对象
     * @throws IOException IO异常
     */
    public JsonObject getJsonObject(HttpServletRequest request) throws IOException {
        String jsonString = getStrFromInsByCode(request.getInputStream(), "utf-8");
        LOGGER.info("request:" + jsonString);
        JsonParser jsonParser = new JsonParser();
        return (JsonObject) jsonParser.parse(jsonString);
    }

    /**
     * 解析json数组
     *
     * @param request 请求对象
     * @return JsonArray json数组
     * @throws IOException IO异常
     */
    public JsonArray getJsonArray(HttpServletRequest request) throws IOException {
        String jsonString = getStrFromInsByCode(request.getInputStream(), "utf-8");
        LOGGER.info("request:" + jsonString);
        JsonParser jsonParser = new JsonParser();
        return (JsonArray) jsonParser.parse(jsonString);
    }


    /**
     * 解析json对象工具方法
     *
     * @param is   输入流
     * @param code 字符码
     * @return builder 具有json格式的字符串
     */
    public static String getStrFromInsByCode(InputStream is, String code) {
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new InputStreamReader(is, code));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line + "\n");
            }
        } catch (Exception e) {
//            e.printStackTrace();
            LOGGER.info("error:" + e.getMessage());
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
//                e.printStackTrace();
                LOGGER.info("error:" + e.getMessage());
            }
        }
        return builder.toString();
    }
}
